﻿Imports System.Data.SqlClient
Public Class frmPaiementParai
    'Matériels
    'variables 
    Dim rest As Double
    Dim Line As ListViewItem
    Dim idPai As Integer
    Dim cmbDeselctLst As Boolean = False
    Dim nbrEvenCmbCall As Int16 = 0

    Dim lstVieSelectCmb As Boolean = False
    Dim nbrEvenCallLst As Int16 = 0

    'Fonctions et procédures
    Public Sub remplirLstPayementParraineur()
        lstPaiement = New List(Of paiement)
        Cmd = New SqlCommand("select * from paiements" &
                            " where idPai in(" &
                                " select idPai from paiementParrain" &
                                " where idParrain = " & somParrain.idParain & ")", Con)
        open()
        Dr = Cmd.ExecuteReader
        If Dr.HasRows Then
            While Dr.Read
                lstPaiement.Add(New paiement With {.idPai = Dr.GetInt32(0), .montant = Dr.GetDouble(1), .type = Dr.GetString(2)})
            End While
        End If
        Dr.Close()
        cnClose()
    End Sub

    'End
    Private Sub frmPymntParrain_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        frmMesParraines.Enabled = True
    End Sub

    Private Sub frmPymntParrain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            remplirLstPayementParraineur()
            rest = Math.Round(somParrain.somme, 2)
            For Each payParrai In lstPaiement
                rest -= Math.Round(payParrai.montant, 2)
                Line = New ListViewItem(New String() {payParrai.idPai, payParrai.montant, payParrai.type})
                lstViwPay.Items.Add(Line)
            Next

            txtSomRest.Text = Math.Round(rest, 2)
            txtTotal.Text = Math.Round(somParrain.somme, 2)
            cmbTypePay.SelectedIndex = 0
        Catch ex As Exception
            MsgBox("Une erreur c'est produite, veuillez informer l'administrateur de l'application !!!" & Environment.NewLine & "Déscription de l'erreur :" & Environment.NewLine & ex.Message, MsgBoxStyle.Critical, "Erreur")
        End Try
    End Sub

    Private Sub btnPayer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPayer.Click
        Try
            If lstViwPay.SelectedItems.Count <= 0 Then
                Dim prix As Double = 0
                Dim prixVrai As Boolean = False
                Dim idNomin As Integer 'pour stocker la valeur de l'idNominatif ajouté
                'Rassuré le prix
                If Not String.IsNullOrWhiteSpace(txtSomPay.Text) And Not String.IsNullOrEmpty(txtSomPay.Text) Then
                    Double.TryParse(txtSomPay.Text, prix)
                End If
                If prix > 0 And prix <= rest Then
                    prixVrai = True
                ElseIf prix <= 0 Or prix > rest Then
                    MsgBox("Prix incorrecte!!!" & Environment.NewLine & "- Vous avez entrez beaucoup de virgules" & Environment.NewLine &
                           "- le prix est supèrieur du reste à payer" & Environment.NewLine &
                           "- le prix est null", MsgBoxStyle.Critical, "Erreur")
                    Exit Sub
                End If
                'End

                If cmbTypePay.SelectedIndex = 1 Then
                    If IsNothing(cheq.numChe) Then
                        MsgBox("Vous n'avez pas rempli le Chéque!!!", MsgBoxStyle.Critical, "Erreur")
                        Exit Sub
                    End If
                End If
                If cmbTypePay.SelectedIndex = 2 Then
                    If IsNothing(effetObj.numEffet) Then
                        MsgBox("Vous n'avez pas rempli l'Effet!!!", MsgBoxStyle.Critical, "Erreur")
                        Exit Sub
                    End If
                End If

                If cmbTypePay.SelectedIndex = 3 Then
                    If IsNothing(objVirement.numCompte) Then
                        MsgBox("Vous n'avez pas rempli le virement!!!", MsgBoxStyle.Critical, "Erreur")
                        Exit Sub
                    End If
                End If


                If prixVrai Then
                    Cmd = New SqlCommand("INSERT INTO [paiements]([montant],[type])VALUES(@montant,@type)", Con)
                    Cmd.Parameters.Add("@montant", SqlDbType.Float)
                    Cmd.Parameters("@montant").Value = Math.Round(prix, 2)
                    Cmd.Parameters.Add("@type", SqlDbType.VarChar)
                    Cmd.Parameters("@type").Value = cmbTypePay.Text
                    open()
                    Cmd.ExecuteNonQuery()

                    Cmd.CommandText = "select @@IDENTITY"
                    Dim idPai As Integer = Cmd.ExecuteScalar
                    Cmd.CommandText = "INSERT INTO paiementParrain([idPai],[idParrain])VALUES(" & idPai & "," & somParrain.idParain & ")"
                    Cmd.ExecuteNonQuery()
                    cnClose()

                    rest -= prix
                    txtSomRest.Text = Math.Round(rest, 2)

                    remplirLstPayementParraineur()
                    lstViwPay.Items.Clear()
                    For Each payParrai In lstPaiement
                        Line = New ListViewItem(New String() {payParrai.idPai, payParrai.montant, payParrai.type})
                        lstViwPay.Items.Add(Line)
                    Next


                    If Not IsNothing(nomin.nom) Then
                        'cette partie ajoute le nominatif et retourne l'id de ce dernier
                        Cmd.CommandText = "ajouterNominatif"
                        Cmd.CommandType = CommandType.StoredProcedure
                        Cmd.Parameters.Add("@nom", SqlDbType.VarChar)
                        Cmd.Parameters("@nom").Value = nomin.nom
                        Cmd.Parameters.Add("@Prenom", SqlDbType.VarChar)
                        Cmd.Parameters("@Prenom").Value = nomin.prenom
                        Cmd.Parameters.Add("@idNomin", SqlDbType.Int)
                        Cmd.Parameters("@idNomin").Direction = ParameterDirection.Output
                        open()
                        Cmd.ExecuteNonQuery()
                        idNomin = Cmd.Parameters("@idNomin").Value
                    End If

                    Dim idPay As Integer
                    If cmbTypePay.SelectedIndex <> 0 Then
                        idPay = lstPaiement.Max(Function(x) x.idPai)
                    End If

                    If cmbTypePay.SelectedIndex = 2 Then
                        If Not IsNothing(effetObj.numEffet) Then
                            Cmd = New SqlCommand("INSERT INTO [Effet] " & _
                                                 "VALUES(" & idPai & ",@numChe,'" & Format(effetObj.dteEffet, "MM-dd-yyyy") & "'," & nullPourDate(effetObj.dteRetrait) & ",'" & Format(effetObj.dateEcheance, "MM-dd-yyyy") & "'," & convertToBit(cheq.nominatif) & ",@banqueDestinataire,@banqueDestinateur,'P')", Con)
                            'MsgBox(cheq.dteRetra)
                            Cmd.Parameters.Add("@numChe", SqlDbType.VarChar)
                            Cmd.Parameters("@numChe").Value = effetObj.numEffet

                            Cmd.Parameters.Add("@banqueDestinataire", SqlDbType.VarChar)
                            Cmd.Parameters("@banqueDestinataire").Value = effetObj.banqueDestinataire

                            Cmd.Parameters.Add("@banqueDestinateur", SqlDbType.VarChar)
                            Cmd.Parameters("@banqueDestinateur").Value = effetObj.banqueDestinateur
                            open()
                            Cmd.ExecuteNonQuery()
                            If Not IsNothing(nomin.nom) Then
                                Cmd.CommandText = "insert into nominEffet values(" & idNomin & "," & idPai & ")"
                                Cmd.ExecuteNonQuery()
                            End If

                            cnClose()
                            effetObj = Nothing
                            nomin = Nothing
                        End If
                    ElseIf cmbTypePay.SelectedIndex = 1 Then
                        If Not IsNothing(cheq.numChe) Then
                            Cmd = New SqlCommand("INSERT INTO [cheques] " & _
                                                 "VALUES(" & idPai & ",@numChe," & convertToBit(cheq.nominatif) & "," & nullPourDate(cheq.dteRetra) & ",'" & Format(cheq.dateChequ, "MM-dd-yyyy") & "',@banqueDestinateur,@banqueDestinataire,'P')", Con)
                            'MsgBox(cheq.dteRetra)
                            Cmd.Parameters.Add("@numChe", SqlDbType.VarChar)
                            Cmd.Parameters("@numChe").Value = cheq.numChe

                            Cmd.Parameters.Add("@banqueDestinateur", SqlDbType.VarChar)
                            Cmd.Parameters("@banqueDestinateur").Value = cheq.banqueDestinateur

                            Cmd.Parameters.Add("@banqueDestinataire", SqlDbType.VarChar)
                            Cmd.Parameters("@banqueDestinataire").Value = cheq.banqueDestinataire

                            open()
                            Cmd.ExecuteNonQuery()

                            If Not IsNothing(nomin.nom) Then
                                Cmd.CommandText = "insert into nominCheq values(" & idPai & "," & idNomin & ")"
                                Cmd.ExecuteNonQuery()
                            End If
                            cnClose()
                            cheq = Nothing
                            nomin = Nothing
                        End If
                    ElseIf cmbTypePay.SelectedIndex = 3 Then
                        If Not IsNothing(objVirement.numCompte) Then
                            Cmd = New SqlCommand("INSERT INTO [virement] " &
                                                "VALUES (" & idPai & ",@numCompte,@banqueDestinataire, " &
                                                "@banqueDestinateur,'" & Format(objVirement.dateVirement, "MM-dd-yyyy") & "',@nom,'P')", Con)

                            Cmd.Parameters.Add("@numCompte", SqlDbType.VarChar)
                            Cmd.Parameters("@numCompte").Value = objVirement.numCompte
                            Cmd.Parameters.Add("@banqueDestinataire", SqlDbType.VarChar)
                            Cmd.Parameters("@banqueDestinataire").Value = objVirement.banqueDestinataire
                            Cmd.Parameters.Add("@banqueDestinateur", SqlDbType.VarChar)
                            Cmd.Parameters("@banqueDestinateur").Value = objVirement.banqueDestinateur
                            Cmd.Parameters.Add("@nom", SqlDbType.VarChar)
                            Cmd.Parameters("@nom").Value = objVirement.nom

                            open()
                            Cmd.ExecuteNonQuery()
                            cnClose()
                            objVirement = Nothing
                        End If
                    End If

                    MsgBox("La somme est bien ajoutée à ma liste payement", MsgBoxStyle.Information, "succès")
                    txtSomPay.Clear()
                    cmbTypePay.SelectedIndex = 0
                End If
            Else
                MsgBox("Rassurez qu'aucaun payement n'est séléctionné", MsgBoxStyle.Critical, "Erreur")
            End If
        Catch ex As Exception
            MsgBox("Une erreur c'est produite, veuillez informer l'administrateur de l'application !!!" & Environment.NewLine & "Déscription de l'erreur :" & Environment.NewLine & ex.Message, MsgBoxStyle.Critical, "Erreur")
        End Try
    End Sub

    Private Sub txtSomPay_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSomPay.KeyPress
        Dim allowedChars As String = "1234567890,"
        If e.KeyChar = ChrW(8) Then
            e.Handled = False
        ElseIf allowedChars.IndexOf(e.KeyChar) = -1 Then
            ' Invalid Character
            e.Handled = True
        End If
    End Sub

    Private Sub btnSupp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSupp.Click
        Try

            Cmd = New SqlCommand("DELETE FROM paiements WHERE idPai = " & idPai, Con)
            open()
            Cmd.ExecuteNonQuery()


            For Each lstIt As ListViewItem In lstViwPay.Items
                If CInt(lstIt.SubItems(0).Text) = idPai Then
                    rest += Double.Parse(lstIt.SubItems(1).Text)
                    txtSomRest.Text = Math.Round(rest, 2)
                    txtSomPay.Clear()
                    lstIt.Remove()
                    Exit For
                End If
            Next
            cnClose()

            MsgBox("La somme est bien supprimée de ma liste payement", MsgBoxStyle.Information, "succès")
        Catch ex As Exception
            MsgBox("Une erreur c'est produite, veuillez informer l'administrateur de l'application !!!" & Environment.NewLine & "Déscription de l'erreur :" & Environment.NewLine & ex.Message, MsgBoxStyle.Critical, "Erreur")
        End Try
    End Sub

    Private Sub lstViwPay_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstViwPay.Click
        cmbDeselctLst = False
    End Sub

    Private Sub lstViwPay_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstViwPay.SelectedIndexChanged
        Try
            If Not cmbDeselctLst Then
                If lstViwPay.SelectedItems.Count > 0 Then
                    idPai = CInt(lstViwPay.SelectedItems(0).SubItems(0).Text)
                    'remplir le cheque et le nominatif
                    Dim typePai As String = ""
                    If lstViwPay.SelectedItems(0).SubItems(2).Text = "Chéque" Then
                        typePai = "nominCheq"
                        Cmd = New SqlCommand("select * from cheques where idPai= " & idPai, Con)
                        open()
                        Dr = Cmd.ExecuteReader
                        If Dr.HasRows Then
                            Dr.Read()
                            With cheq
                                .idPai = Dr.GetInt32(0)
                                .numChe = Dr.GetString(1)
                                .nominatif = Dr.GetBoolean(2)
                                .dteRetra = convertNullToDate(Dr(3))
                                .dateChequ = Dr(4)
                                .banqueDestinataire = Dr("banqueDestinataire")
                                .banqueDestinateur = Dr("banqueDestinateur")
                                .typePersonne = "P"
                            End With
                        End If
                        Dr.Close()
                    ElseIf lstViwPay.SelectedItems(0).SubItems(2).Text = "Effet" Then
                        typePai = "nominEffet"
                        Cmd = New SqlCommand("select * from Effet where idPai= " & idPai, Con)
                        open()
                        Dr = Cmd.ExecuteReader
                        If Dr.HasRows Then
                            Dr.Read()
                            With effetObj
                                .idPai = Dr.GetInt32(0)
                                .numEffet = Dr.GetString(1)
                                .dteEffet = Dr(2)
                                .dteRetrait = convertNullToDate(Dr(3))
                                .dateEcheance = Dr(4)
                                .nominatif = Dr.GetBoolean(5)
                                .banqueDestinataire = Dr("banqueDestinataire")
                                .banqueDestinateur = Dr("banqueDestinateur")
                                .typePersonne = "P"
                            End With
                        End If
                        Dr.Close()
                    ElseIf lstViwPay.SelectedItems(0).SubItems(2).Text = "Virement" Then
                        Cmd = New SqlCommand("select * from virement where idPai= " & idPai, Con)
                        open()
                        Dr = Cmd.ExecuteReader
                        If Dr.HasRows Then
                            Dr.Read()
                            With objVirement
                                .idPai = Dr.GetInt32(0)
                                .numCompte = Dr.GetString(1)
                                .banqueDestinataire = Dr.GetString(2)
                                .banqueDestinateur = Dr.GetString(3)
                                .dateVirement = Dr(4)
                                .nom = Dr.GetString(5)
                                .typePersonne = "P"
                            End With
                        End If
                        Dr.Close()
                    End If

                    If cheq.numChe <> Nothing Or effetObj.numEffet <> Nothing Then
                        Cmd = New SqlCommand("select * from nominatifA " &
                                            "where idNomin in (select " & typePai & ".idNomin from " & typePai & " where " & typePai & ".idPai = " & idPai & ")", Con)
                        Dr = Cmd.ExecuteReader
                        If Dr.HasRows Then
                            Dr.Read()
                            With nomin
                                .idNomin = Dr.GetInt32(0)
                                .idPai = cheq.idPai
                                .nom = Dr.GetString(1)
                                .prenom = Dr.GetString(2)
                            End With
                        End If
                        Dr.Close()
                        cnClose()
                    End If
                    'end remplissage

                    txtSomPay.Text = lstViwPay.SelectedItems(0).SubItems(1).Text
                    lstVieSelectCmb = True
                    cmbTypePay.SelectedItem = lstViwPay.SelectedItems(0).SubItems(2).Text
                Else
                    txtSomPay.Clear()
                    cmbTypePay.SelectedIndex = 0
                    cheq = Nothing
                    effetObj = Nothing
                    nomin = Nothing
                End If
            End If
            cmbDeselctLst = False
        Catch ex As Exception
            MsgBox("Une erreur c'est produite, veuillez informer l'administrateur de l'application !!!" & Environment.NewLine & "Déscription de l'erreur :" & Environment.NewLine & ex.Message, MsgBoxStyle.Critical, "Erreur")
        End Try
    End Sub
    Private Sub cmbTypePay_SelectionChangeCommitted(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbTypePay.SelectionChangeCommitted
        lstVieSelectCmb = False
    End Sub
    Private Sub cmbTypePay_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbTypePay.SelectedIndexChanged

        If nbrEvenCmbCall > 0 Then
            If cmbTypePay.SelectedIndex = 1 Then
                btnCheqFrm.Visible = True
            Else
                btnCheqFrm.Visible = False
            End If

            If cmbTypePay.SelectedIndex = 2 Then
                btnEffet.Visible = True
            Else
                btnEffet.Visible = False
            End If

            If cmbTypePay.SelectedIndex = 3 Then
                btnVirementFrm.Visible = True
            Else
                btnVirementFrm.Visible = False
            End If

            If Not lstVieSelectCmb Then
                txtSomPay.Clear()
                For Each it As ListViewItem In lstViwPay.SelectedItems
                    cmbDeselctLst = True
                    it.Selected = False
                Next
            End If
            lstVieSelectCmb = False
        End If
        nbrEvenCmbCall += 1
    End Sub

    Private Sub btnCheqFrm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheqFrm.Click
        If lstViwPay.SelectedItems.Count <= 0 Then
            cheq = Nothing
            nomin = Nothing
        End If
        Me.Enabled = False
        frm = Me
        frmCheques.Show()
    End Sub

    Private Sub btnEffet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEffet.Click
        If lstViwPay.SelectedItems.Count <= 0 Then
            effetObj = Nothing
            nomin = Nothing
        End If
        Me.Enabled = False
        frm = Me
        FrmEffet.Show()
    End Sub

    Private Sub btnVirementFrm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVirementFrm.Click
        If lstViwPay.SelectedItems.Count <= 0 Then
            objVirement = Nothing
        End If
        Me.Enabled = False
        frm = Me
        frmVirement.Show()
    End Sub

    Private Sub txtTotal_MouseHover(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTotal.MouseHover
        Me.ToolTip1.Show(txtTotal.Text, txtTotal, 0, 30, 5000)
    End Sub

    Private Sub txtSomRest_MouseHover(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSomRest.MouseHover
        Me.ToolTip1.Show(txtSomRest.Text, txtSomRest, 0, 30, 5000)
    End Sub

    Private Sub txtTotal_MouseLeave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTotal.MouseLeave
        Me.ToolTip1.Hide(txtTotal)
    End Sub

    Private Sub txtSomRest_MouseLeave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSomRest.MouseLeave
        Me.ToolTip1.Hide(txtSomRest)
    End Sub
End Class